package com.zpark.servlet.servlet_config;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

/**
 * @PackageName: com.zpark.servlet.servlet_config
 * @ClassName: ServletConfigDemo02
 * @Description:
 * @author: RZS
 * @date: 2023/3/6  15:56
 */
@WebServlet(urlPatterns = "/sc02.do",
    initParams = {
        @WebInitParam(name = "username", value = "root"), @WebInitParam(name = "pwd", value = "123456")
    }
)
public class ServletConfigDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取当前servlet的config对象
        ServletConfig servletConfig = getServletConfig();

        PrintWriter writer = resp.getWriter();
        // 根据初始化参数名 name，返回对应的初始化参数值。
        String zs = servletConfig.getInitParameter("ZS");
        writer.println("<h2>"+ zs +"</h2>");

        writer.println("<h2>"+ servletConfig.getInitParameter("username") +"</h2>");

        // 获取初始化参数的名字枚举
        Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();
        while (initParameterNames.hasMoreElements()) {
            // 循环取出参数名字
            String name = initParameterNames.nextElement();
            // 根据 初始化参数名字获取对应的值
            String value = servletConfig.getInitParameter(name);
            writer.println("<h2>"+ name + ": " + value +"</h2>");
        }

        writer.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
